import { useState, useEffect, useRef } from "react"
import L from 'leaflet';
// import 'leaflet/dist/leaflet.css';
import lessModule from "./index.module.less"
import { $eventBus, $EventBus_off, $EventBus_on } from "../../../../common/utils";

// 主页-全景监控页面-地图组件
interface homePageMapComponentInterface {
    styleData: object
    funcList?: Array<Function>
}

const HomePage_MapComponent: React.FC<homePageMapComponentInterface> = (props) => {
    let [map, setMap] = useState<L.Map | undefined>(undefined)
    const funcList = useRef<Array<Function>>([])
    // 地图初始化
    const mapInit = () => {

        // map = L.map('map').setView([22.524037, 113.923483], 16);
        map = L.map('map').setView([22.531861, 114.118623], 10);
        setMap(map)
        // const api = 'http://192.168.1.21:12138/index/map/四川省/{z}/{x}/{y}.png?{Math.random()}'
        L.tileLayer("http://222.212.85.72:15935/index/zhi_liu_pian_ci_map/{z}/{x}/{y}/tile.png", {
        // L.tileLayer("http://basemaps.cartocdn.com/light_nolabels/{z}/{x}/{y}{r}.png", {
            minZoom: 5,
            maxZoom: 15,
            attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors',
            updateWhenIdle: true, // 仅在地图空闲时加载新的瓦片
        }).addTo(map);
    }

    const judgeExecute_propsFuncList = (value: boolean) => {
        if (props.funcList?.length) {
            props.funcList.forEach((item) => {
                "isRefresh" in item && item["isRefresh"] === value && item["func"](map)
            })
            funcList.current = props.funcList
        }
    }
    // 广播函数数据
    const eventBusFuncData = {
        homePageMapComponent_tooltip: (data) => {


            switch (data) {
                // 放大
                case "enlarge":
                    map?.setZoom(map?.getZoom() + 1)
                    break;
                // 缩小
                case "narrow":
                    map?.setZoom(map?.getZoom() - 1)
                    break;
                // 测距
                case "ranging":

                    break;
            }

        }
    }

    const on_zoom = () => {
        if (props.funcList?.length) {
            props.funcList.forEach((item) => {
                item["isZoomRefresh"] && item["func"](map)
            })
        }
    }

    useEffect(() => {
        !funcList.current.length && judgeExecute_propsFuncList(false)
        judgeExecute_propsFuncList(true)
        map?.on('zoomend', on_zoom)
        return () => {
            map?.off('zoomend', on_zoom);
        }
    }, [props.funcList])

    useEffect(() => {
        mapInit()
        $EventBus_on(eventBusFuncData)
        // 销毁
        return () => {
            map?.remove()
            $EventBus_off(eventBusFuncData)
        }
    }, [])

    return (
        <div className={lessModule["homePageMapComponent"]}>
            <div id="map" style={props.styleData}></div>
        </div>
    )
}
export default HomePage_MapComponent